package com.xb.cloud.usercenter.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.xb.cloud.common.sms.SmsSender;
import com.xb.cloud.common.util.BeanUtils;
import com.xb.cloud.gateway.client.ReturnCodes;
import com.xb.cloud.gateway.client.ReturnUtils;
import com.xb.cloud.gateway.client.RtnInfo;
import com.xb.cloud.order.service.client.SellOrderService;
import com.xb.cloud.order.service.client.SellOrderSkuService;
import com.xb.cloud.order.service.client.bo.OrderQueryBo;
import com.xb.cloud.order.service.client.bo.SoDeliveryBo;
import com.xb.cloud.order.service.client.bo.SoSkuSummeryBo;
import com.xb.cloud.order.service.client.bo.SoSummaryBo;
import com.xb.cloud.order.service.client.model.OrderDeliveryInfo;
import com.xb.cloud.product.merchant.service.client.ShopService;
import com.xb.cloud.product.merchant.service.client.bo.ShopBo;
import com.xb.cloud.user.service.client.SmsSendLogService;
import com.xb.cloud.usercenter.client.vo.OrderDetailsVo;
import com.xb.cloud.usercenter.client.vo.OrderQueryVo;
import com.xb.cloud.usercenter.client.vo.SellOrderSkuVo;
import com.xb.cloud.usercenter.client.vo.SellOrderVo;
import com.xb.cloud.usercenter.client.vo.UserAddressVo;
import com.xb.cloud.usercenter.config.AppConfig;
import com.xb.cloud.usercenter.service.SellOrderApiService;

@Service
public class SellOrderApiServiceImpl implements SellOrderApiService {

	private static final Logger LOGGER = LoggerFactory.getLogger(SellOrderApiServiceImpl.class);

	@Resource
	SellOrderService sellOrderService;

	@Resource
	SellOrderSkuService sellOrderSkuService;

	@Resource
	ShopService shopService;

	@Resource
	SmsSendLogService smsSendLogService;
	
	@Resource
	SmsSender smsSender;

	@Override
	public RtnInfo getOrderListByStatus(OrderQueryVo orderQueryVo) {
		int defaultPageSize = AppConfig.DEFAULT_PAGE_SIZE;

		long companyId = orderQueryVo.getCompanyId();
		long currentUserId = orderQueryVo.getCurrentUserId();
		int pageNum = orderQueryVo.getPageNum();
		int pageSize = orderQueryVo.getPageSize();
		String status = orderQueryVo.getStatus();

		// 当前页默认为1
		pageNum = pageNum <= 0 ? 1 : pageNum;
		// 分页大小默认为10
		pageSize = pageSize < defaultPageSize ? defaultPageSize : pageSize;

		OrderQueryBo orderQueryBo = new OrderQueryBo();
		orderQueryBo.setCompanyId(companyId);
		orderQueryBo.setEndUserId(currentUserId);

		try {
			orderQueryBo.setStatus(Integer.valueOf(status));
		} catch (NumberFormatException e) {
			orderQueryBo.setStatus(null);
		}

		int count = sellOrderService.countUserOrderByStatus(orderQueryBo);
		if (count <= 0) {
			return ReturnUtils.success();
		}

		int maxPageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
		if (pageNum > maxPageNum) {
			return ReturnUtils.error(ReturnCodes.PAGE_NUM_INVALID);
		}

		orderQueryBo.setStartPage((pageNum - 1) * pageSize);
		orderQueryBo.setPageSize(pageSize);

		List<SoSummaryBo> sellOrderBoList = sellOrderService.getUserOrderListByStatus(orderQueryBo);
		List<Long> orderIds = new ArrayList<>();
		List<Long> shopIds = new ArrayList<>();
		for (SoSummaryBo sellOrderBo : sellOrderBoList) {
			orderIds.add(sellOrderBo.getId());// order item 查询条件
			shopIds.add(sellOrderBo.getShopId());
		}

		List<ShopBo> shopList = shopService.getShopListByIds(shopIds);
		Map<Long, ShopBo> shopMap = new HashMap<>();
		for (ShopBo shopBo : shopList) {
			shopMap.put(shopBo.getId(), shopBo);
		}

		List<SoSkuSummeryBo> sellOrderSkuList = sellOrderSkuService.getOrderSkuListByOrderIdList(orderIds);
		Map<Long, List<SellOrderSkuVo>> sellOrderSkuMap = new HashMap<>();
		for (SoSkuSummeryBo sellOrderSkuBo : sellOrderSkuList) {
			List<SellOrderSkuVo> items = null;
			SellOrderSkuVo orderSkuVo = new SellOrderSkuVo();
			BeanUtils.copyProperties(sellOrderSkuBo, orderSkuVo);

			Long soId = sellOrderSkuBo.getSoId();
			if (sellOrderSkuMap.get(soId) == null) {
				items = new ArrayList<>();
				items.add(orderSkuVo);
				sellOrderSkuMap.put(soId, items);
			} else {
				items = sellOrderSkuMap.get(soId);
				items.add(orderSkuVo);
			}
		}

		List<SellOrderVo> sellOrderVoList = new ArrayList<>();
		for (SoSummaryBo soSummaryBo : sellOrderBoList) {
			SellOrderVo sellOrderVo = new SellOrderVo();
			Long soId = soSummaryBo.getId();
			sellOrderVo.setId(soId);
			sellOrderVo.setShopId(soSummaryBo.getShopId());
			sellOrderVo.setCreateTime(soSummaryBo.getCreateTime());
			sellOrderVo.setSkuAmount(soSummaryBo.getSkuAmount());
			sellOrderVo.setOrderAmount(soSummaryBo.getOrderAmount());
			sellOrderVo.setStatus(soSummaryBo.getStatus());
			sellOrderVo.setDeliveryFee(soSummaryBo.getDeliveryFee());

			ShopBo shopBo = shopMap.get(soSummaryBo.getShopId());
			sellOrderVo.setShopName(shopBo.getShopNameCn());
			sellOrderVo.setShopHomeUrl(shopBo.getShopHomeUrl());

			List<SellOrderSkuVo> items = sellOrderSkuMap.get(soId);
			int skuCount = 0;
			for (SellOrderSkuVo skuItem : items) {
				skuCount += skuItem.getSkuNum();
			}
			sellOrderVo.setSkuCount(skuCount);
			sellOrderVo.setItems(items);
			sellOrderVoList.add(sellOrderVo);
		}

		return ReturnUtils.success(sellOrderVoList);
	}

	@Override
	public RtnInfo getOrderDetailsById(OrderQueryVo orderQueryVo) {

		Long soId = orderQueryVo.getOrderId();
		SoDeliveryBo soDeliveryBo = sellOrderService.getOrderDetailsById(soId);
		if (soDeliveryBo == null) {
			return ReturnUtils.error(ReturnCodes.ORDER_NOT_EXIST);
		}

		SoSummaryBo soSummaryBo = soDeliveryBo.getSoSummaryBo();
		OrderDeliveryInfo deliveryInfo = soDeliveryBo.getDeliveryInfo();

		List<SoSkuSummeryBo> sellOrderSkuList = sellOrderSkuService.getOrderSkuListByOrderId(soId);
		ShopBo shopBo = shopService.getById(soSummaryBo.getShopId());

		SellOrderVo sellOrderVo = new SellOrderVo();
		sellOrderVo.setId(soId);
		sellOrderVo.setShopId(soSummaryBo.getShopId());
		sellOrderVo.setStatus(soSummaryBo.getStatus());
		sellOrderVo.setOrderAmount(soSummaryBo.getOrderAmount());
		sellOrderVo.setSkuAmount(soSummaryBo.getSkuAmount());
		sellOrderVo.setCreateTime(soSummaryBo.getCreateTime());
		sellOrderVo.setDeliveryFee(soSummaryBo.getDeliveryFee());
		sellOrderVo.setShopName(shopBo.getShopNameCn());
		sellOrderVo.setShopHomeUrl(shopBo.getShopHomeUrl());
		sellOrderVo.setSoUserRemark(soSummaryBo.getSoUserRemark());
		sellOrderVo.setPaymentConfirmTime(soSummaryBo.getPaymentConfirmTime());

		List<SellOrderSkuVo> items = new ArrayList<>();
		int skuCount = 0;
		for (SoSkuSummeryBo soSkuSummeryBo : sellOrderSkuList) {
			SellOrderSkuVo orderSkuVo = new SellOrderSkuVo();
			BeanUtils.copyProperties(soSkuSummeryBo, orderSkuVo);
			items.add(orderSkuVo);
			skuCount += orderSkuVo.getSkuNum();
		}
		sellOrderVo.setSkuCount(skuCount);
		sellOrderVo.setItems(items);

		UserAddressVo userAddressVo = new UserAddressVo();
		if (deliveryInfo != null) {
			sellOrderVo.setReceiveTime(deliveryInfo.getReceiveTime());
			sellOrderVo.setDeliveryTime(deliveryInfo.getDeliveryTime());
			userAddressVo.setDetailAddress(deliveryInfo.getGoodReceiverAddress());
			userAddressVo.setReceiverName(deliveryInfo.getGoodReceiverName());
			userAddressVo.setPhone(deliveryInfo.getGoodReceiverPhone());
		}

		OrderDetailsVo orderDetailsVo = new OrderDetailsVo();
		orderDetailsVo.setSellOrderVo(sellOrderVo);
		orderDetailsVo.setUserAddressVo(userAddressVo);

		return ReturnUtils.success(orderDetailsVo);
	}

	@Override
	public RtnInfo getOrderCountWithStatus(OrderQueryVo orderQueryVo) {
		OrderQueryBo orderQueryBo = new OrderQueryBo();
		orderQueryBo.setCompanyId(orderQueryVo.getCompanyId());
		orderQueryBo.setEndUserId(orderQueryVo.getCurrentUserId());

		try {
			orderQueryBo.setStatus(Integer.valueOf(orderQueryVo.getStatus()));
		} catch (NumberFormatException e) {
			orderQueryBo.setStatus(null);
		}

		// 状态code=订单数量
		Map<String, Integer> orderCountWithStatus = sellOrderService.getOrderCountWithStatus(orderQueryBo);

		return ReturnUtils.success(orderCountWithStatus);
	}

	@Override
	public RtnInfo notifyMerchantOrderPayed(Long orderId) {

		// TODO:防刷策略（验证码未过期只能发送一次，一天5次）
//		ServiceReturnInfo serviceReturnInfo = smsSendLogService.countByPhoneNumWithDay(companyId, phoneNum);
//		int count = 0;
//		if (ServiceReturnUtils.isSuccess(serviceReturnInfo)) {
//			count = (int) serviceReturnInfo.getData();
//		} else {
//			return ReturnUtils.error(ReturnCodes.SYSTEM_EXCEPTION);
//		}
//
//		if (count > AppConfig.VERIFYCODE_SEND_LIMIT) {
//			return ReturnUtils.error(ReturnCodes.VERIFYCODE_SEND_LIMIT_REACHED);
//		}
//
//		String verifycodeKey = String.format(AppConfig.VERIFYCODE_KEY, companyId, phoneNum);
//		if (CacheUtil.exists(verifycodeKey)) {
//			// 验证码未过期，提示发送频繁
//			return ReturnUtils.error(ReturnCodes.VERIFYCODE_SEND_FREQUENTLY);
//		}

		

		SoDeliveryBo soDetails = sellOrderService.getOrderDetailsById(orderId);
		StringBuffer content = new StringBuffer();
		SoSummaryBo soSummaryBo = soDetails.getSoSummaryBo();
		content.append(soSummaryBo.getId()).append(" 金额：").append(soSummaryBo.getOrderAmount());
		
		Long shopId = soSummaryBo.getShopId();
		ShopBo shopBo = shopService.getById(shopId);
		String phoneNum = shopBo.getShopContactsMob();
		
		Boolean successed = smsSender.sendTextMsgCommon(phoneNum, content.toString(), SmsSender.ORDERPAYED_TEMPLATE);

		if (successed) {
			return ReturnUtils.success();
		} else {
			return ReturnUtils.error(ReturnCodes.NOTIFY_MERCHANT_SEND_FAILED);
		}

	}

}
